/**
 * This file is Copyright © 2008 Software Craftsmen Limited. All Rights Reserved.
 */
package com.softwarecraftsmen.orogeny.application.compilation;

import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.NonNls;

import java.net.URL;

public final class ClassToResourceUrl
{
	@NonNls
	private static final String PrefixedClassExtension = ".class";
	private static final char Slash = '/';
	private static final char Period = '.';

	public static boolean isClassResource(final @NotNull String relativeUrl)
	{
		return relativeUrl.endsWith(PrefixedClassExtension);
	}

	@NotNull
	public static String relativeUrlRepresentingAResourceOnTheClassPathToClassName(final @NotNull String relativeUrl)
	{
		if (!isClassResource(relativeUrl))
		{
			throw new IllegalArgumentException("relativeUrl is not a class resource");
		}
		return relativeUrl.substring(0, relativeUrl.length() - PrefixedClassExtension.length()).replace(Slash, Period);
	}

	@Nullable
	public static URL toExtantResourceUrl(final @NotNull Class<?> clazz, final @NotNull ClassLoader classLoader)
	{
		return classLoader.getResource(classNameToRelativeUrlRepresentingAResourceOnTheClassPath(clazz.getName()));
	}

	@Nullable
	public static URL toExtantResourceUrl(final @NotNull String className, final @NotNull ClassLoader classLoader)
	{
		return classLoader.getResource(classNameToRelativeUrlRepresentingAResourceOnTheClassPath(className));
	}

	@NotNull
	private static String classNameToRelativeUrlRepresentingAResourceOnTheClassPath(final @NotNull String className)
	{
		return className.replace(Period, Slash) + PrefixedClassExtension;
	}

	private ClassToResourceUrl()
	{}
}
